import math
from builtins import range
import numpy as np
from random import shuffle
from past.builtins import xrange

def softmax_loss_naive(W, X, y, reg):
    """
    Softmax loss function, naive implementation (with loops)

    Inputs have dimension D, there are C classes, and we operate on minibatches
    of N examples.

    Inputs:
    - W: A numpy array of shape (D, C) containing weights.
    - X: A numpy array of shape (N, D) containing a minibatch of data.
    - y: A numpy array of shape (N,) containing training labels; y[i] = c means
      that X[i] has label c, where 0 <= c < C.
    - reg: (float) regularization strength

    Returns a tuple of:
    - loss as single float
    - gradient with respect to weights W; an array of same shape as W
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    #############################################################################
    # TODO: Compute the softmax loss and its gradient using explicit loops.     #
    # Store the loss in loss and the gradient in dW. If you are not careful     #
    # here, it is easy to run into numeric instability. Don't forget the        #
    # regularization!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    sample_num = X.shape[0]
    dim_num = X.shape[1]
    class_num =W.shape[1]

    scores = X.dot(W)
    exp = math.e**scores
    exp_sum = np.sum(exp,axis=1)
    P = exp/exp_sum.reshape(500,-1)
    #y_pred = np.argsort(scores,axis=1)
    #correct_scores = scores[np.arange(X.shape[0]),y_pred]

    '''使用定义式
    for i in range(sample_num):
        for j in range(class_num):
            if j==y[i]:
                loss -= math.log(likelyhoods[i,j])

    loss += np.sum(reg*W*W)
    loss /= sample_num
    '''

    '''使用导出式'''
    for i in range(sample_num):
        loss += (-scores[i,y[i]]+np.log(exp_sum[i]))

    loss += reg * np.sum(W * W)
    loss /= sample_num



    '''按照单个权重的推导
    for i in range(sample_num):
        for a in range(dim_num):
            for b in range(class_num):
                if b==y[i]:
                    dW[a,b] += (P[i,b]-1)*X[i,a]
                else:
                    dW[a,b] += P[i, b]*X[i, a]
    dW/=sample_num
    '''

    '''使用列直接计算'''
    for i in range(sample_num):
        for j in range(class_num):
            if j==y[i]:
                dW[:,j] += (P[i,j]-1)*X[i]
            else:
                dW[:, j] += P[i, j] * X[i]

    dW += reg * np.sum(2 * W)
    dW /= sample_num


    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    return loss, dW


def softmax_loss_vectorized(W, X, y, reg):
    """
    Softmax loss function, vectorized version.

    Inputs and outputs are the same as softmax_loss_naive.
    """
    # Initialize the loss and gradient to zero.
    loss = 0.0
    dW = np.zeros_like(W)

    #############################################################################
    # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
    # Store the loss in loss and the gradient in dW. If you are not careful     #
    # here, it is easy to run into numeric instability. Don't forget the        #
    # regularization!                                                           #
    #############################################################################
    # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

    sample_num = X.shape[0]
    dim_num = X.shape[1]
    class_num = W.shape[1]

    #loss computation
    scores = X.dot(W) #计算得分矩阵
    es = math.e**scores #计算每个得分的幂次
    P = es/np.sum(es,axis=1).reshape(-1,1) #计算概率矩阵
    loss = -np.sum(np.log(P[np.arange(sample_num),y]))  #计算交叉熵损失
    loss += np.sum(reg*W*W)
    loss /= sample_num

    '''循环版本
    #dW computation
    for i in range(sample_num):
        dW += P[i,:]*(X[i].reshape(-1,1)) #详细看公式
        dW[:,y[i]] -= X[i]
    '''

    '''非循环版本'''
    y_lable = np.zeros_like(P)
    y_lable[np.arange(sample_num),y]=1.0 #把对应样本的正确类别标出来
    dW = X.T.dot(P-y_lable)
    dW /= sample_num


    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    return loss, dW
